import { assert, assetManager, AudioClip, AudioSource, log, _decorator, Component, resources, AssetManager } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('AudioManager')
export class AudioManager extends Component {
    //  _audioSource: AudioSource;

    @property(AudioSource)
    public _audioSource: AudioSource = null!;
    // private static _cachedAudioClipMap: Record<string, AudioClip> = {};

    /***动态加载音乐资源类部分****/

    onLoad() {
        // 获取 AudioSource 组件
        const audioSource = this.node.getComponent(AudioSource)!;
        // 检查是否含有 AudioSource，如果没有，则输出错误消息
        assert(audioSource);
        // 将组件赋到全局变量 _audioSource 中
        this._audioSource = audioSource;
    }

    playi(name: string) {
        const path = `audio/music/${name}`;
        // let cachedAudioClip = AudioManager._cachedAudioClipMap[path];
        assetManager.resources?.load(path, AudioClip, (err, Clipi) => {
            if (err) {
                console.warn(err);
                return;
            }
            //绑定读取到的音效
            this._audioSource.clip = Clipi
            // 播放音乐
            this._audioSource.play();
        });
    }


    continueplay() {
        this._audioSource.play();
    }

    pausei() {
        // 暂停音乐
        this._audioSource.pause();
    }

    stopi() {
        // 暂停音乐
        this._audioSource.stop();
    }

    /***************************************************/




    //音效播放
    // init AudioManager in GameRoot component.
    playEffet(name: string, volumeScale: number) {
        
        const path = `audio/sound/${name}`;
        // let cachedAudioClip = AudioManager._cachedAudioClipMap[path];
        assetManager.resources?.load(path, AudioClip, (err, clip) => {
            if (err) {
                console.warn(err);
                return;
            }

            let nclip = clip
            this._audioSource.playOneShot(clip, volumeScale);

        })
    }

}